package com.auok.Command;

import com.auok.Entity.UserMessage;
import com.auok.Entity.UserSession;
import com.auok.Message.SendToUserMessage;
import com.auok.ShareData;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;
import java.util.UUID;

@AllArgsConstructor
@Getter
@Setter
public class SendToUserCommand {
    private String toUserId;
    private String content;

    /**
     * 私聊
     *
     * @param fromUserId 来源用户Id
     * @return 用户消息实体
     */
    public UserMessage Exec(String fromUserId) {

        UserSession toUserSession = ShareData.userSessions.get(toUserId);

        UserMessage userMessage = new UserMessage(
                UUID.randomUUID().toString()
                , fromUserId
                , toUserId
                , content
                , new Date()
                , true);

        if (toUserSession == null || toUserSession.getWebSocket() == null) {
            userMessage.setReceived(false);
        } else {
            try {
                new SendToUserMessage(
                        userMessage.getTime()
                        , fromUserId
                        , content)
                        .Send(toUserSession);
            } catch (Exception e) {
                e.printStackTrace();
                userMessage.setReceived(false);
            }

        }


        return userMessage;
    }
}
